﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class GenericParameterConstraintRule : ILRule<GenericParameterConstraintHandle>
    {
        [ILInfo]
        public GenericParameterHandle GenericParameter { get; }

        [ILInfo(true)]
        public EntityHandle Constraint { get; }

        [ILInfo]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public GenericParameterConstraintRule(
            GenericParameterHandle genericParameter,
            EntityHandle constraint)
            : base()
        {
            GenericParameter = genericParameter;
            Constraint = constraint;
        }

        public GenericParameterConstraintRule(MetadataReader reader, GenericParameterConstraintHandle genericParameterConstraintHandle)
            : base(reader)
        {
            GenericParameterConstraint genericParameterConstraint = reader.GetGenericParameterConstraint(genericParameterConstraintHandle);
            GenericParameter = genericParameterConstraint.Parameter;
            Constraint = genericParameterConstraint.Type;
            CustomAttributes = genericParameterConstraint.GetCustomAttributes();
        }

        public override GenericParameterConstraintHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddGenericParameterConstraint(
                genericParameter: GenericParameter,
                constraint: Constraint);
        }
    }
}